<template>
  <div class="container">
    <el-card>
      <el-form
        ref="topForm"
        :model="form"
        @submit.native.prevent
      >
        <div style="display: flex; justify-content: space-between;">
          <span>
            <el-form-item prop="idNum" style="display: inline-block; width: 300px; margin-right: 12px; margin-bottom: 0;">
              <el-input v-model.trim="form.searchParam" clearable placeholder="搜索客户、单据号" />
            </el-form-item>
            <el-button type="primary" @click="queryTableData">搜索</el-button>
          </span>
          <span>
            <el-button v-permission="['f06_01']" type="primary" @click="mannualRecharge">手动充值</el-button>
          </span>
        </div>
      </el-form>
    </el-card>
    <el-card style="margin-top: 12px;">
      <div style="margin-bottom: 22px">
        <el-button
          v-for="item in tableTypeList"
          :key="item.value"
          :type="item.value===tableType ? 'primary': 'default'"
          @click="getTypeTable(item.value)"
        >
          {{ item.label }}
        </el-button>
      </div>
      <BaseTable
        ref="manualRecharge"
        :table-data="tableData"
        :table-list="tableList"
        :loading="manualRechargeLoading"
        :total="total"
        show-index
        show-pagination
        @pagination="handlePagination"
      />
    </el-card>
    <el-dialog
      v-if="visible"
      title="手动充值"
      :visible.sync="visible"
      :close-on-press-escape="false"
      width="700px"
      center
      @open="openManualRechargeDialog"
    >
      <el-form
        ref="addForm"
        v-loading="addFormLoading"
        :model="addForm"
        :rules="addFormRules"
        class="manual-recharge"
      >
        <el-form-item label="请选择客户：" prop="companyId" label-width="150px">
          <el-select
            v-model="addForm.companyId"
            v-loadmore="loadmoreCompany"
            placeholder="请输入客户名称"
            clearable
            filterable
            remote
            :loading="compamyLoading"
            :remote-method="remoteCompany"
            style="width: 100%;"
            @change="companyHandle"
          >
            <el-option
              v-for="item in companyList"
              :key="item.key"
              :value="item.id"
              :label="item.companyNameForeign"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="addform-manual-recharge-sell" label-width="150px">
          <el-row>
            <el-col :span="8">
              <span>销售经理：{{ addForm.companyId && formatUserName(addForm.belongUserName) }}</span>
            </el-col>
            <el-col :span="8">
              <span>客户类型：{{ getDictionaryLabel(addForm.companyTypeCode, company_type) }}</span>
            </el-col>
            <el-col :span="8">
              <span>国家：{{ getDictionaryLabel(addForm.countryCode, country_code) }}</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="充值账户：" prop="accountType" label-width="150px">
          <el-select
            v-model="addForm.accountType"
            clearable
            placeholder="请选择充值账户"
            style="width: 100%"
          >
            <el-option
              v-for="item in account_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>

        </el-form-item>
        <el-form-item label="充值金额：" class="addform-manual-recharge-sell" prop="amount" label-width="150px">
          <div class="d-flex">
            <el-input v-model.trim="addForm.amount" clearable placeholder="请输入充值金额" />
            <span style="margin-left: 10px;">$</span>
          </div>
          <div>
            提示：输入负数为扣减
          </div>
        </el-form-item>
        <el-form-item
          v-if="isShowExpirationTime"
          label="到期时间："
          prop="expiryTime"
          label-width="150px"
        >
          <el-date-picker
            v-model="addForm.expiryTime"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            style="width: 100%;"
            :picker-options="expiryTimeOptions"
          />
        </el-form-item>
        <el-form-item label="备注：" prop="remark" label-width="150px">
          <el-input
            v-model="addForm.remark"
            type="textarea"
            resize="none"
            clearable
            placeholder="请输入备注"
            maxlength="500"
            show-word-limit
            :rows="5"
          />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button v-loading="submitLoading" type="primary" @click="submitForm">提交</el-button>
        <el-button @click="visible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import BaseTable from '@/components/BaseTable'
import { formatTime, createUnionId, getDictionaryLabel, formatMoneyAmount, formatUserName } from '@/utils/tools'
import { getList, createManualRecharge } from '@/service/manualRecharge'
import { accountList } from '@/service/accountManage'
import { mapState, mapActions } from 'vuex'

const rechargeAmountValidator = (rule, value, callback) => {
  const reg = /^-?(0|[1-9]\d*)(\.[\d]{1,2})?$/
  if (value === '') {
    return callback(new Error('请输入充值金额'))
  } else if (!reg.test(value)) {
    return callback(new Error('充值金额必须为数字，且小数点后面最多两位数'))
  }
  return callback()
}

export default {
  name: 'ManualRecharge',
  components: {
    BaseTable
  },
  data() {
    return {
      form: {
        searchParam: ''
      },
      visible: false,
      formatUserName,
      getDictionaryLabel,
      tableData: [],
      tableList: [
        {
          label: '客户名称',
          prop: 'companyNameForeign'
        },
        {
          label: '客户类型',
          prop: 'companyTypeCode',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = getDictionaryLabel(row[prop], this.company_type)
            return <span>{ text }</span>
          }
        },
        {
          label: '销售经理',
          prop: 'belongUserName',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = formatUserName(row[prop])
            return <span>{ text }</span>
          }
        },
        {
          label: '国家',
          prop: 'countryCode',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = getDictionaryLabel(row[prop], this.country_code)
            return <span>{text}</span>
          }
        },
        {
          label: '单据号',
          prop: 'transactionFlowNo'
        },
        {
          label: '充值类型',
          prop: 'accountType',
          render: (node, data) => {
            const { row, column: { prop }} = data
            const text = this.getNumberStatusText(this.account_type, row[prop])
            return <span>{ text }</span>
          }
        },
        {
          label: '充值金额（美元）',
          prop: 'changeAmount',
          render: (h, data) => {
            const { row, column: { prop }} = data
            const text = row[prop] || row[prop] === 0 ? formatMoneyAmount(row[prop]) : '-'
            return <span>{ text }</span>
          }
        },
        {
          label: '到期时间',
          prop: 'afterExpiryTime',
          width: '134px',
          render: function(node, data) {
            const { row, column: { prop }} = data
            const text = formatTime(row[prop])
            return <span>{{ text }}</span>
          }
        },
        {
          label: '操作时间',
          prop: 'updateTime',
          width: '134px',
          render: function(node, data) {
            const { row, column: { prop }} = data
            const text = formatTime(row[prop])
            return <span>{{ text }}</span>
          }
        },
        {
          label: '操作人',
          prop: 'updateUser'
        },
        {
          label: '备注',
          prop: 'remark'
        }
      ],
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      addForm: {
        companyId: '', // 客户（公司）id
        accountType: '', // 充值账户
        amount: '', // 充值金额
        expiryTime: '', // 到期时间
        remark: '', // 备注
        countryCode: '', // 国家
        belongUserName: '', // 销售经理
        companyTypeCode: ''
      },
      addFormRules: {
        companyId: [{ required: true, message: '请输入客户名称', trigger: ['change', 'blur'] }],
        accountType: [{ required: true, message: '请选择充值账户', trigger: ['change', 'blur'] }],
        amount: [{ required: true, validator: rechargeAmountValidator, trigger: 'blur' }],
        expiryTime: [{ required: true, message: '请选择到期时间', trigger: ['change', 'blur'] }]
      },
      tableType: 3,
      tableTypeList: [
        {
          label: '返点记录',
          value: 3
        },
        {
          label: '授信记录',
          value: 1
        }
      ],
      compamyLoading: false,
      addFormLoading: false,
      manualRechargeLoading: false,
      companyList: [],
      companyPageData: {
        pageSize: 10,
        pageNum: 1
      },
      companyTotal: 0,
      searchCompanyVal: '',
      submitLoading: false,
      isShowExpirationTime: true,
      expiryTimeOptions: {
        disabledDate: time => {
          const nowDate = new Date()
          const yesterDate = nowDate.setTime(nowDate.getTime() - 24 * 60 * 60 * 1000)
          return time < yesterDate
        }
      }
    }
  },
  computed: {
    ...mapState({
      country_code: state => state.base.country_code,
      account_type: state => state.base.account_type,
      company_type: state => state.base.company_type
    })
  },
  watch: {
    'addForm.amount': {
      handler(newVal) {
        const floatNum = parseFloat(newVal)
        if (floatNum < 0) {
          this.isShowExpirationTime = false
        } else {
          this.isShowExpirationTime = true
        }
      }
    }
  },
  mounted() {
    this.getDictionary()
    this.getCompanyList('')
    this.queryTableData()
  },
  methods: {
    ...mapActions({
      getBaseDataList: 'base/getBaseDataList'
    }),
    getDictionary() {
      this.getBaseDataList({ type: 'country_code' })
      this.getBaseDataList({ type: 'account_type' })
      this.getBaseDataList({ type: 'company_type' })
    },
    async initTableData() {
      this.manualRechargeLoading = true
      const params = {
        pageNum: this.pageIndex,
        pageSize: this.pageSize,
        flowType: this.tableType,
        ...this.form
      }
      const { records, total } = await getList({ ...params }).finally(() => { this.manualRechargeLoading = false })
      this.tableData = records || []
      this.total = total
    },
    queryTableData() {
      this.pageIndex = 1
      this.pageSize = 10
      this.$refs.manualRecharge.pageIndex = 1
      this.$refs.manualRecharge.pageSize = 10
      this.initTableData()
    },
    submitForm() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          this.submitLoading = true
          this.addFormLoading = true
          await createManualRecharge(Object.assign(this.addForm, {
            expiryTime: this.addForm.expiryTime ? `${formatTime(this.addForm.expiryTime, 'YYYY-MM-DD')} 23:59:59` : ''
          })).finally(() => {
            this.submitLoading = false
            this.addFormLoading = false
          })
          this.$message({
            message: '充值成功',
            type: 'success'
          })
          this.queryTableData()
          this.visible = false
        } else {
          return false
        }
      })
    },
    handlePagination(data) {
      const { pageIndex, pageSize } = data
      this.pageIndex = pageIndex
      this.pageSize = pageSize
      this.initTableData()
    },
    getTypeTable(type) {
      this.tableType = type
      this.queryTableData()
    },
    loadmoreCompany() {
      if (this.companyList.length >= this.companyTotal) return
      this.companyPageData.pageNum++
      this.getCompanyList('')
    },
    remoteCompany(query) {
      this.companyList = []
      this.searchCompanyVal = query
      this.companyPageData.pageNum = 1
      setTimeout(() => {
        this.getCompanyList(query)
      }, 200)
    },
    async getCompanyList(query) {
      this.compamyLoading = true
      const { records, total } = await accountList({ companyNameForeign: query, ...this.companyPageData }).finally(() => {
        this.compamyLoading = false
      })
      records.forEach(item => {
        item.key = createUnionId()
      })
      this.companyTotal = total
      this.companyList = [...this.companyList, ...records]
    },
    async openManualRechargeDialog() {
      await this.$nextTick()
      this.$refs.addForm?.clearValidate()
    },
    initAddform() {
      Object.keys(this.addForm).forEach(key => {
        this.addForm[key] = ''
      })
    },
    companyHandle(val) {
      if (val) {
        const item = this.companyList.find(it => it.id === val)
        this.addForm.belongUserName = item.belongUserName
        this.addForm.companyTypeCode = item.companyTypeCode
        this.addForm.countryCode = item.countryCode
      }
    },
    mannualRecharge() {
      this.visible = true
      this.initAddform()
    },
    getNumberStatusText(list, status) {
      const item = list.find(it => +it.value === +status) || {}
      const text = item.label ? item.label : status
      return text
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  margin: 12px;
  width: calc(100% - 24px);
}
</style>

<style lang="scss">
.manual-recharge {
  .el-form-item__content{
    display: flex
  }
  .addform-manual-recharge-sell {
    .el-form-item__content{
    display: block
  }
  }
}

</style>
